package com.skyinno.mrms.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.validation.BindingResult;
import org.springframework.web.servlet.view.AbstractView;

public class PlainView extends AbstractView {
	public static final String DEFAULT_CONTENT_TYPE = "text/plain";

	private ObjectMapper objectMapper = new ObjectMapper();

	private JsonEncoding encoding = JsonEncoding.UTF8;

	public PlainView() {
		this.setContentType(DEFAULT_CONTENT_TYPE);
		this.setExposePathVariables(false);
	}

	@Override
	protected void prepareResponse(HttpServletRequest request,
			HttpServletResponse response) {
		this.setResponseContentType(request, response);
		response.setCharacterEncoding(this.encoding.getJavaName());
		response.addHeader("Pragma", "no-cache");
		response.addHeader("Cache-Control", "no-cache, no-store, max-age=0");
		response.addDateHeader("Expires", 1L);
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		Set<String> renderedAttributes = model.keySet();
		for (Map.Entry<String, Object> entry : model.entrySet()) {
			if (!(entry.getValue() instanceof BindingResult)
					&& renderedAttributes.contains(entry.getKey())) {
				result.put(entry.getKey(), entry.getValue());
			}
		}
		JsonGenerator generator = this.objectMapper.getJsonFactory()
				.createJsonGenerator(response.getOutputStream(), this.encoding);
		this.objectMapper.writeValue(generator, result.size() == 1 ? result
				.values().iterator().next() : result);
	}
}
